/**
 * 存放交互逻辑代码
 */
//javavscript 模块化
var seckill = {
    //封装秒杀相关ajax的url
    URL: {
        now: function () {
            return "/seckill/time/now";
        },
        exposer : function (seckillId) {
            return "/seckill/"+seckillId+"/exposer";
        },
        excution : function (seckillId ,md5) {
            return '/seckill/'+seckillId+'/'+md5+'/execution';
        }

    },
    //处理秒杀逻辑
    HandleSeckill : function (seckillId,node) {
        //获取秒杀地址，控制显示逻辑，执行秒杀

        node.hide().
        html('<button class="btn btn-success btn-lg" id="killBtn">开始秒杀</button>');//给个按钮
        $.post(seckill.URL.exposer(seckillId),{},function (result) {
            //在回调函数中执行交互流程
            if(result && result['success']){
                var exposer = result['date'];
                if(exposer['exposed']){
                    //开启秒杀
                    //获取秒杀地址
                    md5 = exposer['md5'];
                    var killUrl = seckill.URL.excution(seckillId,md5);
                    console.log('killUrl'+killUrl);

                    //绑定一次点击事件
                    $('#killBtn').one('click',function () {
                        //执行秒杀请求操作
                        //1.先禁用按钮
                        $(this).addClass('disable');
                        //2.发送秒杀请求，执行秒杀
                        $.post(killUrl,{},function (result) {
                            console.log('result+++++' + result);
                            console.log('success' + result['success']);
                            if(result && result['success']){
                                var killResult = result['date'];
                                var state = killResult['state'];
                                var stateInfo = killResult['stateInfo'];
                                //显示秒杀结果
                                node.html('<button class="btn btn-success btn-lg" >'+stateInfo+'</button>');
                            }else {
                                //重复秒杀
                                var killResult = result['date'];
                                var state = killResult['state'];
                                var stateInfo = killResult['stateInfo'];
                                excution = result['date'];
                                console.log("message++"+excution['stateInfo']);
                                node.html('<button class="btn btn-danger btn-lg" >'+stateInfo+'</button>');
                            }
                        });
                    })
                    node.show();
                }else {
                    //未开启秒杀
                    var now = exposer['now'];
                    var start = exposer['start'];
                    var end = exposer['end'];
                    //重新进入计时逻辑
                    seckill.countdown(seckillId,now,start,end);
                }
            }else {
                console.log('result:'+result);
            }
        });
    },
    //验证电话知否合法
    validatePhone: function (phone) {
        if (phone && phone.length == 11 && !isNaN(phone)) {

            return true;
        } else {
            return false;
        }
    },
    //时间判断函数
    countdown: function (seckillId, nowTime, startTime, endTime) {
        var seckillBox = $('#seckill-box');
        if(nowTime > endTime){
            $('#BoxHeand').attr("class","panel panel-danger text-center");
            $('#H2Heand').attr("class","text-center text-warning");
            seckillBox.html('秒杀结束');
        }else if (nowTime < startTime){
            var killTime = new Date(startTime);
            //时间变化都会回调方法中的函数
            console.log(Format(killTime,"yyyy-MM-dd HH:mm:ss"));

            seckillBox.countdown(killTime,function (event) {
                $('#BoxHeand').attr("class","panel panel-success text-center");
                $('#H2Heand').attr("class","text-center text-primary");
                //时间格式
                var format = event.strftime('秒杀倒计时 ： %D 天  %H 时 %M 分 %S 秒');
                seckillBox.html(format);
                //时间完成后回调事件
            }).on('finish.countdown',function () {
                //获取秒杀地址，控制显示逻辑，执行秒杀
                seckill.HandleSeckill(seckillId,seckillBox);
            });
        }else{
            //秒杀开始
            seckill.HandleSeckill(seckillId,seckillBox);
        }
    },
    detail: {
        //详情页秒杀逻辑
        init: function (params) {
            //手机验证和登录逻辑，计时交互

            //规划交互流程
            var killPhone = $.cookie('killPhone');

            //验证手机号
            if (!seckill.validatePhone(killPhone)) {
                //绑定手机号
                //控制输出
                var killPhoneModel = $('#killPhoneModel');
                //显示弹出层
                killPhoneModel.modal({
                    show: true,//显示弹出层
                    backdrop: 'static',//禁止位置关闭
                    keyboard: false//禁止键盘
                });
                $('#killPhoneBtn').click(function () {
                    var inputPhone = $('#killPhoneKey').val();
                    if (seckill.validatePhone(inputPhone)) {
                        //电话写入cookie
                        console.log("killPhone" + killPhone);
                        //expires:7,表示7天
                        /*
                        第二种写法，精确到时分秒
                         var cookietime = new Date();
                         var starTime = cookietime.getTime();
                         var date_1 = starTime + (30 * 24 * 60 * 60 * 1000);
                         cookietime.setTime(date_1);//coockie保存30天 //注释的地方不理它。

                         $.cookie("ReVisit", "ReVisit", {expires:cookietime, path:"/"});  //代表30天，这种写法可以精准到时、分、秒。
                         */
                        $.cookie('killPhone', inputPhone, {expires: 7, path: '/seckill'});
                        //刷新页面
                        window.location.reload();
                    } else {
                        $('#killPhoneMessage').hide().html('<label class="label label-danger">手机号错误！</label>').show(300);
                    }
                });
            }
            //已经登录
            var startTime = params['startTime'];
            var endTime = params['endTime'];
            var seckillId = params['seckillId'];
            $.get(seckill.URL.now(), {}, function (result) {
                console.log(result['success']);
                console.log(result['date']);
                if (result && result['success']) {
                    var nowTime = result['date'];
                    //时间判断
                    seckill.countdown(seckillId,nowTime,startTime,endTime);
                } else {
                    console.log('result' + result);
                }
            })

        }
    }
}

//格式化工具
function Format(now,mask)
{
    var d = now;
    var zeroize = function (value, length)
    {
        if (!length) length = 2;
        value = String(value);
        for (var i = 0, zeros = ''; i < (length - value.length); i++)
        {
            zeros += '0';
        }
        return zeros + value;
    };

    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0)
    {
        switch ($0)
        {
            case 'd': return d.getDate();
            case 'dd': return zeroize(d.getDate());
            case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
            case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
            case 'M': return d.getMonth() + 1;
            case 'MM': return zeroize(d.getMonth() + 1);
            case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
            case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
            case 'yy': return String(d.getFullYear()).substr(2);
            case 'yyyy': return d.getFullYear();
            case 'h': return d.getHours() % 12 || 12;
            case 'hh': return zeroize(d.getHours() % 12 || 12);
            case 'H': return d.getHours();
            case 'HH': return zeroize(d.getHours());
            case 'm': return d.getMinutes();
            case 'mm': return zeroize(d.getMinutes());
            case 's': return d.getSeconds();
            case 'ss': return zeroize(d.getSeconds());
            case 'l': return zeroize(d.getMilliseconds(), 3);
            case 'L': var m = d.getMilliseconds();
                if (m > 99) m = Math.round(m / 10);
                return zeroize(m);
            case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
            case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
            case 'Z': return d.toUTCString().match(/[A-Z]+$/);
            // Return quoted strings with the surrounding quotes removed
            default: return $0.substr(1, $0.length - 2);
        }
    });
};